"""
初始化订单记录数据库
"""
import json
import os
from datetime import datetime
from .models import OrderRecord
from .sqlalchemy_database import SQLAlchemyDatabaseManager

def import_order_record_data():
    """
    导入order_record_data.json数据到数据库
    """
    db = SQLAlchemyDatabaseManager()
    session = db.get_session()
    
    try:
        # 获取数据文件路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(current_dir))), "data")
        json_file = os.path.join(data_dir, "order_record_data.json")
        
        if not os.path.exists(json_file):
            print(f"订单记录数据文件不存在: {json_file}")
            return
            
        # 读取JSON数据
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            
        # 导入数据
        for item in data:
            # 转换日期时间字符串为datetime对象
            create_at = datetime.fromisoformat(item['create_at']) if item.get('create_at') else None
            update_at = datetime.fromisoformat(item['update_at']) if item.get('update_at') else None
            buy_at = datetime.fromisoformat(item['buy_at']) if item.get('buy_at') else None
            offer_at = datetime.fromisoformat(item['offer_at']) if item.get('offer_at') else None
            
            record = OrderRecord(
                account_id=item.get('account_id'),
                account_name=item.get('account_name'),
                script_id=item.get('script_id'),
                script_name=item.get('script_name'),
                task_id=item.get('task_id'),
                task_name=item.get('task_name'),
                order_no=item.get('order_no'),
                pay_order_no=item.get('pay_order_no'),
                wait_payment_data_no=item.get('wait_payment_data_no'),
                assetid=item.get('assetid'),
                name=item.get('name'),
                price=item.get('price'),
                game=item.get('game'),
                goods_id=item.get('goods_id'),
                market_hash_name=item.get('market_hash_name'),
                paintwear=item.get('paintwear'),
                expect_income=item.get('expect_income'),
                buy_status=item.get('buy_status', 0),
                pay_type=item.get('pay_type'),
                offer_status=item.get('offer_status', 0),
                offer_times=item.get('offer_times', 0),
                offer_fail_desc=item.get('offer_fail_desc'),
                create_at=create_at,
                update_at=update_at,
                buy_at=buy_at,
                offer_at=offer_at
            )
            session.add(record)
            
        session.commit()
        print("订单记录数据导入成功")
        
    except Exception as e:
        session.rollback()
        print(f"导入订单记录数据时发生错误: {str(e)}")
    finally:
        session.close()

if __name__ == "__main__":
    import_order_record_data()
